package com.hibox.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hibox.common.annotation.Anonymous;
import com.hibox.common.core.domain.AjaxResult;
import com.hibox.common.core.redis.RedisCache;
import com.hibox.common.utils.SecurityUtils;
import com.hibox.common.utils.ServletUtils;
import com.hibox.common.utils.http.HttpUtils;
import com.hibox.common.utils.ip.AddressUtils;
import com.hibox.common.utils.ip.IpUtils;
import com.hibox.common.utils.uuid.IdUtils;
import com.hibox.constant.MemberConstant;
import com.hibox.domain.Member;
import com.hibox.service.MemberService;
import com.hibox.util.JustAuthUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hibox.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * AuthJust三方登录
 *
 * @author WangFK
 * @version 1.0
 * @since 2023/8/17 20:23
 */
@RestController
@RequestMapping("/api/ucenter/wx")
@Slf4j
@Anonymous
public class LoginConrotller {

    @Resource
    private JustAuthUtil justAuthUtil;
    @Resource
    private MemberService memberService;
    @Resource
    private RedisCache redisCache;

    @GetMapping("/login")
    public void renderAuthWechat(HttpServletResponse response) throws IOException {
        renderAuth("wechat_open", response);
    }

    @GetMapping("/login/{source}")
    public void renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
        log.info("进入render：" + source);
        if (ObjectUtil.isEmpty(source)) {
            source = "wechat_open";
        }
        AuthRequest authRequest = justAuthUtil.getAuthRequest(source);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info(authorizeUrl);
        response.sendRedirect(authorizeUrl);
    }

    @GetMapping("/callback")
    public AjaxResult loginWechat(AuthCallback callback) {
        return login("wechat_open", callback);
    }

    @GetMapping("/callback/{source}")
    public AjaxResult login(@PathVariable("source") String source, AuthCallback callback) {
        log.info("进入callback：" + source + " callback params：" + JSONObject.toJSONString(callback));
        String ipAddr = IpUtils.getIpAddr(ServletUtils.getRequest());
        String realAddressByIP = AddressUtils.getRealAddressByIP(ipAddr);
        System.out.println("ip:" + ipAddr);
        System.out.println("ipAddress:" + realAddressByIP);
        AuthRequest authRequest = justAuthUtil.getAuthRequest(source);
        AuthResponse response = authRequest.login(callback);
        Member member = new Member();
        HashMap map = JSONUtil.toBean(JSONUtil.toJsonStr(response.getData()), HashMap.class);
        String openId = map.get("uuid").toString();

        member.setOpenId(openId);

        member.setNickName(map.get("nickname").toString());
        member.setAvatar(map.get("avatar").toString());
        LambdaUpdateWrapper<Member> lqw = new LambdaUpdateWrapper<Member>()
                .eq(Member::getOpenId, openId);
        List<Member> list = memberService.list(lqw);
        // 登录IP
        String loginIp = IpUtils.getIpAddr(ServletUtils.getRequest());
        member.setLoginIp(loginIp);
        // 登录IP地址
        member.setIpAddress(AddressUtils.getRealAddressByIP(loginIp));
        // 登录时间
        member.setLoginDate(DateUtil.date());
        // 三方登录类型
        member.setLoginType(source);
        // 修改 三方登录
        if (ObjectUtil.isNotEmpty(list)) {
            member.setId(list.get(0).getId());
            memberService.updateById(member);
        } else {
            // 新增三方登录
            member.setMemberName("Hi-Box_" + IdUtils.fastSimpleUUID());
            memberService.save(member);
        }
        member = memberService.getById(member.getId());
        String key = MemberConstant.MEMBER_INFO + member.getId();
        redisCache.setCacheObject(key, member, 1, TimeUnit.HOURS);

        return AjaxResult.success(member);
    }


}
